package com.example.qt.ptplatform.filter;

import com.example.qt.ptplatform.utils.JwtUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class JwtAuthenticationFilter implements Filter {

    // Java 8 兼容方式初始化不可变 Set
    private static final Set<String> EXCLUDE_PATHS = Collections.unmodifiableSet(
            new HashSet<>(Arrays.asList(
                    "/user/login",
                    "/user/register",
                    "/torrent/getCoverImage",
                    "/seed/addSeed",
                    "/download/getfile",
                    "/user/get-avatar",
                    "/user/checkCardTime",
                    "/torrent/findAllTorrentList",
                    "/torrent/announce",

                    "/comments/favorites",
                    "/comments/favorites/check",
                    "/comments/listByTorrentId",
                    "/comments/delete",
                    "/commentImage/upload",
                    "/comments/listByTorrentId",
                    "/comments/submit"
                    // 可以继续添加其他不需要拦截的接口路径
            ))
    );

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String path = httpRequest.getRequestURI();

        // 如果是排除路径，则直接放行
        if (EXCLUDE_PATHS.contains(path)) {
            chain.doFilter(request, response);
            return;
        }

        String authHeader = httpRequest.getHeader("Authorization");

        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);

            try {
                String username = JwtUtil.verifyToken(token);
                httpRequest.setAttribute("username", username);
                chain.doFilter(request, response);
                return;

            } catch (Exception e) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\":401,\"msg\":\"无效的 Token\"}");
                return;
            }
        }

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"code\":401,\"msg\":\"请登录后再操作\"}");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void destroy() {}
}
